package yao.xerophyte.java.thread._volatile;

import java.util.ArrayList;
import java.util.List;

/**
 * volatile只能保证线程间的可见性，不能保证原子性
 */
public class VolatileTest_1 {
    
    volatile int count = 0;
    
    synchronized void m() {
        for (int i = 0; i < 10; i++) {
            System.out.println(Thread.currentThread().getName());
            count++;
        }
    }
    
    public static void main(String[] args) {
        VolatileTest_1 t = new VolatileTest_1();
        List<Thread> threads = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            threads.add(new Thread(t::m, "thread-" + i));
        }
        threads.forEach((o) -> o.start());
        //这里join的原因：不加的话，没等各个线程执行完主线程就打印了
        threads.forEach((o) -> {
            try {
                o.join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
        System.out.println(t.count);
    }
}
